<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Routing\Controller;
use AliyunMNS\CreateQueueAndSendMessage;
use App\Models\Weikong;
use App\Models\Device;
use App\Models\ProjectUser;
use App\Models\AdminUser;
use App\Models\SwitchData;
use App\Models\Lock;
use App\Models\LockRecord;
use App\Models\BatteryConfig;
use App\Models\Battery;
use App\Models\Cabinet;
use App\Models\Project;
use App\Models\SwitchModel;
use App\Handlers\MqttHandler;
use App\Handlers\HuaweiCloudHandler;
use App\Handlers\HaiweiHandler;
use App\Handlers\AliDeviceHandler;
use Illuminate\Support\Facades\Redis;

class ApiController extends Controller{

    public function getDeviceList(Request $request){
        $param = $request->all();
        // $adminProjects = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
        $boxes = Cabinet::where('project_id', $param['projectId'])->where('pid', 0)->get()->toArray();
        $switch= SwitchModel::where('project_id', $param['projectId'])->where('pid', 0)->get()->toArray();
        $info = [];
        if ($boxes) {
            foreach ($boxes as &$oneBox) {
                $oneBox['project_name'] = Project::where('projectId', $oneBox['project_id'])->value('projectname');
                $oneBox['device_type'] = 3;
            }
            $info['box'] = $boxes;
        } 
        if ($switch) {
            foreach ($switch as &$val) {
                $val['project_name'] = Project::where('projectId', $val['project_id'])->value('projectname');
                $val['device_type'] = 4;
            }
            $info['switch'] = $switch;
        }
        if(isset($info)){
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $info]);
        }else {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => []]);
        }
    }
    public function Receive(Request $request){
        $json = $request->all();
        print_r($json);die;
        dump($_POST['aa']);die;
        //if($json['type'] == 1){
            $result = ['resultCode'=>1,'resulMsg'=>'接收成功!','resultBody'=>''];
       // }else{
        //    $result = ['resultCode'=>0,'resulMsg'=>'接收失败!','resultBody'=>''];
        //}
        return $result;
    }

    public function test(){
        $res = \App\Models\Cabinet::select('id', 'box_id', 'group_id')->where('pid', '!=' ,0)->get()->toArray();
        foreach ($res as $one) {
            Redis::sadd(\App\Models\Cabinet::WECON_BOX_LIST, $one['box_id']);
            Redis::sadd(\App\Models\Cabinet::WECON_GROUP_.$one['box_id'], $one['group_id']);
            Redis::set(\App\Models\Cabinet::WECON_GROUP_TO_LOCAL_CABINET_.$one['group_id'], $one['id']);
            Redis::sadd(\App\Models\Cabinet::LOCAL_CABINET_LIST, $one['id']);
            var_dump($one);
            echo "\n";
        }
        // var_dump($res);
        return 'hahha';
        $d['project_id'] = 4;
        $d['cabinet_pid'] = 26;
        $d['cabinet_id'] = 27;
        $d['point_id'] = 192;
        $d['name'] = 'hello joker';
        \App\Models\CabinetAlarmLog::pushMessage($d);
        return 'joker';
        \App\Models\Battery::setSwitchStatus('61b7f6902b2aa20288bbbbd7_Battery_monitor_01', 12.4);
        return 'joker';
        HuaweiCloudHandler::getRuleActionList();
        return 'joker';
        \App\Handlers\MqttHandler::SubscribetoTopic(11);
        return 'joker';
        $cacheKey = 'wecon_sid';
        Cache::forget($cacheKey);
        \App\Handlers\WeconHandler::getSid();
        return;
        $Mns = new CreateQueueAndSendMessage('LTAIXidsHeo1vYeo','vO9c9Yqyha6PNAkFyb4jAQPfJ5rvbU','http://1960429774320704.mns.cn-shanghai.aliyuncs.com/');
        $content = $Mns->run('aliyun-iot-a1BbirCKf77');
        // $content = array(
        //     'json'=>'[{"1":"aaa:5","2":"aab:0","3":"aac:0","4":"aad:26","5":"aae:25","6":"aaf:0","7":"aag:0","8":"aah:0","9":"aai:0","10":"aaj:0","11":"aak:0","12":"aal:0","13":"aam:0","14":"aan:22","15":"aao:0","16":"aap:401","date":"2021-06-09 15:16:06.000","ip":"192.168.1.200","device":"test001"},{"date":"2021-06-09 15:16:06.000","ip":"192.168.1.201","device":"test001"}]',
        //     'type'=>'upload',
        //     'code'=>1
        // );
        $data = [];
        if ($content['type'] == 'upload') {
            $arr = json_decode($content['json'], true);
            foreach ($arr as $one) {
                foreach ($one as $k => $v) {
                    $d['created_at'] = date("Y-m-d H:i:s", strtotime($one['date']));
                    $d['address'] = $one['ip'];
                    $d['pname'] = $one['device'];
                    if ($k != 'date' && $k != 'ip' && $k != 'device') {
                        $temp = explode(":", $v);
                        $d['gatewayId'] = reset($temp);
                        $d['value'] = end($temp) ? strval(end($temp)) : 0;
                        array_push($data, $d);
                    }
                }
            }

        }
        if ($data) {
            DB::table('xfy_weikong')->insert($data);
        }
        return;
    }

    public function getDevices(){
        $device = 'test001';
        $fid = DB::table('xfy_ device')->where(['gatewayId'=>$device])->value('deviceId');
        $pdevices = DB::table('xfy_ device')->where(['pid'=>$fid])->get(['deviceId','gatewayId','Max','Min'])->toArray();
        foreach ($pdevices as $v){
            // if($this->address == $v['gatewayId']){
            //     $pid = $v['deviceId'];
            // }
            $devices = DB::table('xfy_ device') ->where(['pid'=>$pid])->get(['devicename', 'gatewayId'])-> toArray();
        }
        foreach ($devices as $k){
            if($this->gatewayId == $k['gatewayId']){
                $devicename = $k['devicename'];
            }
        }
    }

    //维控推送测试 还要插入一条报警日志
    public function weikongsend(){
        $list = Device::where(['device_type'=>6])->pluck('deviceId')->toArray();
        //获取所有维控采集点
        $point = Device::whereIn('pid',$list)->where('device_type',8)->get()->toArray();
        foreach ($point as $key => $value) {
            //查询不在区间内的异常设备
            $weikong = Weikong::where(['gatewayId'=>$value['gatewayId'],'address'=>$value['group']])->whereNotBetween('value', [$value['Min'], $value['Max']])->orderBy('id','DESC')->first();
            if($weikong){
                //获取设备绑定用户
                $user = ProjectUser::where('projectId',$value['projectId'])->get()->toArray();
                foreach ($user as $k => $val) {
                    //根绝unionid获取公众号openid
                    $openid = AdminUser::where('admin_users.id',$val['user_id'])->join('users','admin_users.unionid','=','users.unionid')->select('users.openid')->get()->toArray();
                    if($openid){
                        foreach ($openid as $o => $vo) {
                            //小程序订阅消息
                            $data = [
                                'template_id' => '890vAF2WMqWtWb6s3lkHXgfkWnHJX499DtAtwpyJrEI', // 所需下发的订阅模板id
                                'touser' => $vo['openid'],     // 接收者（用户）的 openid
                                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                                    'date1' => [
                                        'value' => date('Y-m-d H:i',time()),
                                    ],
                                    'thing2' => [
                                        'value' => $value['gatewayId'],
                                    ],
                                    'thing3' => [
                                        'value' => $value['group'],
                                    ],
                                ],
                            ];
                            $mini = \EasyWeChat::miniProgram();
                            $mini->subscribe_message->send($data);
                            //公众号模板消息
                            // $app = app('wechat.official_account');
                            // $res = $app->template_message->send([
                            //     'touser' => $vo['openid'],
                            //     'template_id' => 'wKqlkfSZPuy3G6iRzVAmlPtTVUvYDuN9WNuTNivMYpY',
                            //     'miniprogram' => [
                            //             'appid' => 'wx301bce58badb7cc3',
                            //             'pagepath' => 'pages/message/message',
                            //     ],
                            //     'data' => [
                            //         "first" => [
                            //             "value"=>'设备报警请及时处理',
                            //             "color"=>"#173177"
                            //         ],
                            //         "keyword1" => [
                            //            "value"=>date('Y-m-d H:i',time()),
                            //            "color"=>"#173177"
                            //         ],
                            //         "keyword2"=> [
                            //            "value"=>$value['gatewayId'],
                            //            "color"=>"#173177"
                            //         ],
                            //         "keyword3"=> [
                            //            "value"=>$value['group'],
                            //            "color"=>"#173177"
                            //         ],
                            //         "remark" => [
                            //             "value"=>'请注意关注设备问题，及时解决！',
                            //             "color"=>"#173177"
                            //         ]
                            //     ],
                            // ]);
                        }
                    }
                }
            }
        }
        // foreach ($arr as $key=>$value){
        //     //大于最大值，小于最小值 报警
        //     if ($value['Max']<$s_arr[$value['gatewayId']]||$value['Min']>$s_arr[$value['gatewayId']]) {
        //         // foreach ($user as $uval){
        //             $res = $app->template_message->send([
        //                 'touser' => $uval['openid'],
        //                 'template_id' => 'wKqlkfSZPuy3G6iRzVAmlPtTVUvYDuN9WNuTNivMYpY',
        //                 'miniprogram' => [
        //                         'appid' => 'wx301bce58badb7cc3',
        //                         'pagepath' => 'pages/message/message',
        //                 ],
        //                 'data' => [
        //                 	"first" => [
        //                 		"value"=>'设备报警请及时处理',
        //                 		"color"=>"#173177"
        //                 	],
        //                 	"keyword1" => [
        //                        "value"=>date('Y-m-d H:i',time()),
        //                        "color"=>"#173177"
        //                     ],
        //                     "keyword2"=> [
        //                        "value"=>$value['gatewayId'],
        //                        "color"=>"#173177"
        //                     ],
        //                     "keyword3"=> [
        //                        "value"=>',',
        //                        "color"=>"#173177"
        //                     ],
        //                     "remark" => [
        //                     	"value"=>'请注意关注设备问题，及时解决！',
        //                     	"color"=>"#173177"
        //                     ]
        //                 ],
        //             ]);
        //             // print_r($res);die;
        //         // }
        //     }
        // }
	}

    public function ceshi(){
        $Mns = new CreateQueueAndSendMessage('LTAIXidsHeo1vYeo','vO9c9Yqyha6PNAkFyb4jAQPfJ5rvbU','http://1960429774320704.mns.cn-shanghai.aliyuncs.com/');
        $content = $Mns->run('aliyun-iot-a1fwasvRTlW');
        //$a = cache::get('test001');
        //$a = cache::pull('current');
        dump($content);
    }

    public function getWeikongSid(){
        $cacheKey = 'wecon_sid';
        $sid = Cache::get($cacheKey);
        if ($sid) {
            return response()->json(['code'=>1, 'sid'=> $sid]);
        } else {
            return response()->json(['code'=>0, 'sid'=> 0]);
        }
    }

    public function getSwitchDataByDevice(Request $request){
        $param = $request->all();
        $device = Device::find($param['deviceId']);
        $redisData = SwitchData::getLatestRedisData($device['wk_machine_code']);
        return response()->json(['code'=>1, 'data'=> $redisData]);
    }

    public function setSwitchStatus(Request $request){
        $param = $request->all();
        $device = Device::find($param['deviceId']);
        $parentDevice = Device::find($device['pid']);
        if ($param['status']) { //开
            $res = SwitchData::setSwitchOn($parentDevice['wk_machine_code'], $param['deviceId'], $device['wk_box_id'], $device['wk_machine_code']);
        } else {    //关
            $res = SwitchData::setSwitchOff($parentDevice['wk_machine_code'], $param['deviceId'], $device['wk_box_id'], $device['wk_machine_code']);
        }
        if ($res) {
            return response()->json(['code'=>1, 'msg' => 'success']);
        } else {
            return response()->json(['code'=>0, 'msg' => 'fail']);
        }
    }

    public function getSwitchGroup(Request $request){
        $list[1] = Device::where(['pid'=>136,'projectId'=>2,'wk_group_id'=>1])->get()->toArray();
        $list[2] = Device::where(['pid'=>136,'projectId'=>2,'wk_group_id'=>2])->get()->toArray();
        $list[3] = Device::where(['pid'=>136,'projectId'=>2,'wk_group_id'=>3])->get()->toArray();
        return response()->json(['code'=>1,'data' =>$list]);
    }

    /**
     * [setSwitchStatusByLevels 根据优先级 整级控制开关]
     * @param Request $request [description]
     */
    public function setSwitchStatusByLevels(Request $request){
        $param = $request->all();
        $projectId = $param['projectId'];
        $level = $param['level'];
        $op = $param['op'];

        $gateways = Device::where('projectId', $param['projectId'])->where('device_type', 10)->whereNotNull('wk_machine_code')->where('pid', 0)->get();
        foreach ($gateways as $oneGateway) {
            $switch = Device::where('pid', $oneGateway['deviceId'])->where('wk_group_id', $param['level'])->first();
            if ($switch) {
                if ($op == 'on') {
                    SwitchData::setSwitchOn($oneGateway['wk_machine_code'], $switch['deviceId'], $switch['wk_box_id'], $switch['wk_machine_code']);
                } elseif ($op == 'off') {
                    SwitchData::setSwitchOff($oneGateway['wk_machine_code'], $switch['deviceId'], $switch['wk_box_id'], $switch['wk_machine_code']);
                }
                sleep(1);
            }
        }
    }

    /**
     * [setBatteryConfig 设置电池设备监控值]
     * @param Request $request [description]
     */
    public function setBatteryConfig(Request $request){
        $param = $request->all();
        $bettery = Device::find($param['deviceId']);
        DB::beginTransaction();
        $flag = true;
        if (isset($param['level_1'])) {
            $res = BatteryConfig::updateConfig($param['deviceId'], 1, $param['level_1']);
            if (!$res) {
                $flag = false;
            }
        }
        if (isset($param['level_2'])) {
            $res = BatteryConfig::updateConfig($param['deviceId'], 2, $param['level_2']);
            if (!$res) {
                $flag = false;
            }
        }
        if (isset($param['level_3'])) {
            $res = BatteryConfig::updateConfig($param['deviceId'], 3, $param['level_3']);
            if (!$res) {
                $flag = false;
            }
        }
        if (!$flag) {
            DB::rollBack();
            return response()->json(['code'=>0, 'msg' => '设置失败，请稍候重试']);
        } else {
            DB::commit();
            return response()->json(['code'=>1, 'msg' => '设置成功']);
        }
    }

    /**
     * 修改分级
     *
     * @param Request $request
     * @return void
     */
    public function changeLevel(Request $request){
        $param = $request->all();
        Device::where('deviceId', $param['deviceId'])->update(['wk_group_id'=>$param['level']]);
        return response()->json(['code'=>1,'msg' =>'修改成功']);
    }

    public function huaweiCallback(Request $request){
        $param = $request->all();
        if (isset($param['notify_data'])) {
            $notifyData = $param['notify_data'];
            if (isset($notifyData['body'])) {
                $notifyDataBody = $notifyData['body'];
                if (isset($notifyDataBody['content'])) {
                    $content = $notifyDataBody['content'];
                    if (isset($content['body']) && $content['body']['AC']) {
                        $vol = round($content['body']['vol'] / 10, 1);
                        Battery::setSwitchStatus($notifyData['header']['device_id'], $vol);
                    }
                }
            }
        }
        error_log("hwmsg = ".print_r($param,1)."\n",3,'/tmp/hw.log');
    }

    /**
     * [getLockList 获取锁列表]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getLockList(Request $request){
        $param = $request->all();
        $adminProjects = ProjectUser::where('user_id', $param['adminId'])->pluck('projectId')->toArray();
        $locks = Lock::whereIn('project_id', $adminProjects)->get()->toArray();
        if ($locks) {
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $locks]);
        } else {
            return response()->json(['code'=>0, 'msg' =>'获取失败', 'data' => []]);
        }
    }

    public function getLockStatus(Request $request){
        $param = $request->all();
        // $lock = Lock::find($param['machineCode']);
        $result = AliDeviceHandler::getDeviceStatus($param['machineCode']);
        if($result['Success']==1){
            return response()->json(['code'=>1, 'msg' =>'获取成功', 'data' => $result['Data']['Status']]);
        }else{
            return response()->json(['code'=>0, 'msg' =>'获取失败', 'data' => []]);
        }
    }

    public function PubLock(Request $request){
        $param = $request->all();
        //再校验一次锁是否在线
        $result = AliDeviceHandler::getDeviceStatus($param['devicename']);
        if($result['Success']!=1||$result['Data']['Status']!='ONLINE'){
            $msg = isset($result['Data']['Status'])?:'连接失败';
            return response()->json(['code'=>0, 'msg' =>$msg]);
        }
        //发送开锁指令
        $comd = array(
            'reqId'=>$param['devicename'],
            'command'=>'open',
            'sendTime'=>time(),
            'ttl'=>10,
            'name'=>'haha',
        );
        //设置wifi指令
        // $comd = array(
        //     'regId'=>'ceshiwifi',
        //     'command'=>'set_wifi',
        //     'sendTime'=>time(),
        //     'ttl'=>'10',
        //     'deviceId'=>'ceshi001',
        //     'body'=>array(
        //         'new'=>'test_123456789'
        //     )
        // );
        $lock = Lock::where('deviceName',$param['devicename'])->first();
        $cmdstr = json_encode($comd);
        $strbase = base64_encode($cmdstr);
        $result = AliDeviceHandler::Pub($lock['productKey'],$param['devicename'],$strbase);
        if($result['Success']==1){
            self::setLockRecord($param);
            return response()->json(['code'=>1, 'msg' =>'指令发送成功']);
        }else{
            return response()->json(['code'=>0, 'msg' =>'指令发送失败']);
        }
    }

    public function setLockRecord($info){
        $param = $info;
        $lock = Lock::where('deviceName',$param['devicename'])->first();
        $admin = AdminUser::find($param['adminId']);

        $oneRecord = new LockRecord();
        $oneRecord->lock_id = $lock['id'];
        $oneRecord->lock_name = $lock['name'];
        $oneRecord->operator_id = $param['adminId'];
        $oneRecord->operator_name = $admin['name'];

        $oneRecord->reason = $param['reason'] ? $param['reason'] : '';
        $oneRecord->materiel = $param['materiel'] ? $param['materiel'] : '';
        $oneRecord->materiel_num = $param['materielNum'] ? $param['materielNum'] : 0;
        $oneRecord->device = $param['device'] ? $param['device'] : '';
        $oneRecord->device_num = $param['deviceNum'] ? $param['deviceNum'] : 0;
        // $end = intval($param['endTime']/1000);
        $oneRecord->end_time = $param['endTime'];

        if (isset($param['note']) && !empty($param['note'])) {
            $oneRecord->note = $param['note'];
        }
        if ($oneRecord->save()) {
            return response()->json(['code'=>1, 'msg' =>'记录成功']);
        } else {
            return response()->json(['code'=>0, 'msg' =>'记录失败，请重试']);
        }
    }

    public function getLockRecordList(Request $request){
        $param = $request->all();
        $page = isset($param['page']) ? $param['page'] : null;
        $size = isset($param['size']) ? $param['size'] : null;

        $res = LockRecord::where('lock_id', $param['lockId'])->orderBy('created_at', 'desc')->paginate($size, ['*'], 'page', $page)->toArray();

        $list['currentPage'] = $res['current_page'];
        $list['list'] = $res['data'];
        $list['lastPage'] = $res['last_page'];
        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data'=>$list]);
    }

    public function getHaiweiData(Request $request){
        $param = $request->all();
        HaiweiHandler::setLatestData($param['DataArray']);
    }

    public function getFakeDatas(){
        $arr = [
            ['name'=>'设备A','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备B','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备C','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备D','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备E','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备F','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备G','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备H','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)],
            ['name'=>'设备I','temp'=>rand(10,15),'current'=>rand(20,30),'fcy'=>rand(5,15)]
        ];
        return response()->json(['code'=>1, 'msg' =>'获取成功', 'data'=>$arr]);
    }
    
}